package com.xxc.exam.service.impl

import com.xxc.batis.service.CrudServiceImpl
import com.xxc.batis.service.MysqlCrudServiceImpl
import com.xxc.common.exceptions.DataConflictException
import com.xxc.common.exceptions.DataNotFoundException
import com.xxc.exam.entity.pojo.Manager
import com.xxc.exam.mapper.ManagerMapper
import com.xxc.exam.service.ManagerService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.lang.Exception
import java.math.BigInteger
import java.sql.Timestamp
import java.util.*

@Service
class ManagerServiceImpl: ManagerService,MysqlCrudServiceImpl<Manager,ManagerMapper>() {

    @Autowired
    lateinit var managerMapper: ManagerMapper

    override fun add(email: String, password: String):BigInteger {
        try{
            val manager = managerMapper.selectOne(Manager(email = email)) as Manager?
            if(manager == null)
            {
                val manager = Manager(email = email,password = password)
                val now = Timestamp.from(Date().toInstant())
                manager.gmtCreate = now
                manager.gmtModified = now
                managerMapper.insert(manager)
                return manager.id!!
            }
        }catch (e:Exception)
        {
            val manager = Manager(email = email,password = password)
            val now = Timestamp.from(Date().toInstant())
            manager.gmtCreate = now
            manager.gmtModified = now
            managerMapper.insert(manager)
            return manager.id!!
        }
        throw DataConflictException("该用户已存在")
    }

    override fun find(email: String, password: String): Manager {
        val manager = managerMapper.selectOne(Manager(email = email)) as Manager?
        if(manager != null)
        {
            val data = manager as Manager
            if (data.password == password) {
                return data
            }else
            {
                throw DataConflictException("用户密码错误")
            }
        }
        else
            throw DataNotFoundException("该用户不存在")
    }



}